<?php
/**
 * Created by PhpStorm.
 * User: 马超
 * Date: 2017/12/11
 * Time: 16:11
 */

namespace console\controllers;

use app\common\corelib\CacheHelper;
use app\common\HttpCurl;
use app\common\WebSocket;
use app\common\WxUtil;
use app\models\Message;
use app\models\User;
use yii\console\Controller;
use yii\console\Exception;
use yii;

class IndexController extends Controller
{
    public function actionRefreshToken(){
        $appid = \Yii::$app->params['wx']['appid'];
        $secret = \Yii::$app->params['wx']['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $data = HttpCurl::get($url);
        CacheHelper::set('access_token',$data['access_token'],$data['expires_in']);
    }

    public function actionGetJsSdkTicket(){
        $access_token = CacheHelper::get('access_token');
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
        $data = HttpCurl::get($url);
        CacheHelper::set('ticket',$data['ticket'],$data['expires_in']);
    }

    public function actionSendMessage(){
        $wxUtil = new WxUtil();
        $access_token = $wxUtil->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
        $user = User::find()->asArray()->all();
        foreach($user AS $key=>$value){
            $data['touser'] = $value['open_id'];
            $data['template_id'] = Yii::$app->params['message']['template_id'];
            $data['url'] = Yii::$app->params['message']['url'];
            $data['data']['first']['value'] = '请记得学习!';
            $res = HttpCurl::get($url,json_encode($data));
        }
        $message = new Message();
        $message->message_title = "小学数学课堂";
        $message->message_content = "小学数学课堂";
        $message->add_time = date('Y-m-d H:i:s');
        $message->save();

    }

    public function actionWebsocket(){
        $config=array(
            'address'=>'0.0.0.0',
            'port'=>'2000',
            'event'=>'WSevent',//回调函数的函数名
            'log'=>true,
        );
        $websocket = new WebSocket($config);
        $websocket->run();

    }






}
